package org.xtetris;

import javax.microedition.lcdui.Graphics;

import org.util.Util;

public class Menu implements Constants{
	public final static int MENU_TYPE_MAIN_MENU = 0;
	public final static int MENU_TYPE_IN_GAME = 1;
	
	public static int GAP_VERTICAL = 5;
	
	private final static String[][] TEXT = 
	{
		{"Start" , "Preference" , "About" , "Exit"},
		{"Back" , "Preference" , "Main menu"},
		{"Start" , "Preference" , "About" , "Exit"},
	};
	
	final int id;
	final Menu parent;
	
	final String[] text;
	int[] itemStyles;
	
	final Engine engine;
	final int x , y;
	int current;
	
	public final static int STYLE_PLAIN_TEXT = 0;
	public final static int STYLE_TOGGLEABLE = 1;
	
	public MenuListener listener;
	
	public Menu(Engine engine, int id , Menu parent , int x ,int y , MenuListener listener){
		this.engine = engine;
		this.id = id;
		this.parent = parent;
		this.text = TEXT[id];
		this.x = x;
		this.y = y;
		
		itemStyles = new int[this.text.length];
		this.listener = listener;
	}
	
	public void paint(Graphics g){
		g.setFont(FONT_MENU);
		
		g.setColor(COLOR_WHITE);
		g.fillRect(0, 0, engine.fullScreenWidth, engine.fullScreenHeight);
		
		int x = this.x;
		int y = this.y;
		
		g.setColor(COLOR_GRAY);
		
//		final int width = Menu.getWidth(id);
		final int width = 100;
		final int height = Menu.getHeight(id);
		
		g.fillRect((engine.fullScreenWidth - width) >> 1, y + current * (FONT_MENU.getHeight() + GAP_VERTICAL), width, FONT_MENU.getHeight());
		
		g.setColor(COLOR_BLACK);
		for (int i = 0; i < text.length; i++) {
			Util.drawString(g, text[i], engine.halfFullScreenWidth, y, Graphics.HCENTER | Graphics.TOP);
			y += FONT_MENU.getHeight() + GAP_VERTICAL;
		}
		
	}
	
	public MenuListener getMenuListener(){
		return listener;
	}
	
	public void setMenuListener(MenuListener listener){
		this.listener = listener;
	}
	
	public void tick(){
		if(engine.isKeyPressed(KEY_UP)){
			current = current <= 0 ? text.length - 1 : current - 1;
		}else if(engine.isKeyPressed(KEY_DOWN)){
			current = (current + 1) % text.length;
		}else if(engine.isKeyPressed(KEY_FIRE)){
			if(listener == null){
				throw new IllegalStateException("no menu listener bound to menu [" + id + "]");
			}else{
				listener.itemSelected(this, current);
			}
		}
	}
	
	public void setStyle4MenuItem(int index , int style){
		itemStyles[index] = style;
	}

	public final static int getWidth(int id){
		int width = 0;
		final String[] text = TEXT[id];
		
		for (int i = 0; i < text.length; i++) {
			width = Math.max(width, FONT_MENU.stringWidth(text[i]));	
		}
		
		return width;
	}
	
	public final static int getHeight(int id){
		final String[] text = TEXT[id];
		return (text.length - 1) * GAP_VERTICAL + FONT_MENU.getHeight() * text.length;
	}
}
